const { list } = require('./mock')
const bodyParser = require('body-parser')
const JWT = require('jsonwebtoken')
const OSS = require('ali-oss')
const path = require("path")
const multipart = require('connect-multiparty');
const multipartMiddleware = multipart();

module.exports = app => {
	// ["去中心化应用", "公链", "联盟链", "layer2", "编程语言"]
	app.use(bodyParser.json())

	app.get('/api/list', (req, res) => {
		const { type = '全部' } = req.query;

		if (type === '全部') {
			res.send(
				{
					code: 200,
					data: {
						type: '全部',
						children: list.reduce((p, n) => {
							return p.concat(n.children)
						}, [])
					},
					message: '数据获取成功'
				}
			)
		} else {
			const item = list.find(v => v.type === type);

			res.send({
				code: 200,
				data: item,
				message: '数据获取成功'
			})
		}
	})

	app.post('/api/login', (req, res) => {
		const { username, password } = req.body;

		if (username === 'admin' && password === '123456') {
			res.send({
				code: 200,
				data: {
					username: 'admin',
					nickname: '张三',
					avator: 'https://robohash.org/2?set=set4',
					id: 1,
					token: JWT.sign({
						username: 'admin',
						nickname: '张三',
						avator: 'https://robohash.org/2?set=set4',
						id: 1,
					}, '666666')
				}
			})
		} else {
			res.send({
				code: 403,
				message: '只有一个账户：admin， 密码： 123456'
			})
		}
	})


	app.post('/api/upload', multipartMiddleware, async (req, res) => {
		
		const client = new OSS({
			// yourregion填写Bucket所在地域。以华东1（杭州）为例，Region填写为oss-cn-hangzhou。
			region: 'oss-cn-shanghai',
			// 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
			accessKeyId: 'LTAI5tHUtUgaEwCpdbks1vH1',
			accessKeySecret: '5SrPlDD8XN5KrRlW9FxLSkQGWcxxO8',
			// 填写Bucket名称。
			bucket: 'xixi-1',
		});

		const result = await client.put(req.files.chunk.originalFilename, path.normalize(req.files.chunk.path))


		res.send({
			"errno": 0, // 注意：值是数字，不能是字符串
			"data": {
				"url": result.url, // 图片 src ，必须
				"alt": "yyy", // 图片描述文字，非必须
				"href": "zzz" // 图片的链接，非必须
			}
		})

	})

	app.post('/api/list', (req, res) => {
		const {
			src,
			title,
			content,
			avator,
			auther,
			type,
			html } = req.body;

		const item = list.find(v => v.type === type);
		if (item) {
			item.children.unshift({
				src,
				title,
				content,
				avator,
				auther,
				html,
				id: Math.random().toString().slice(2)
			})
			res.send({
				code: 200,
				message: '添加成功'
			})
		} else {
			res.send({
				code: 400,
				message: '添加失败'
			})
		}

	})

}